3
3
.
.
4
4
.
.
3
3
C
C
u
u
s
s
t
t
o
o
m
m
V
V
i
i
e
e
w
w
-
-
C
C
o
o
m
m
b
b
i
i
n
n
e
e
I
I
n
n
f
f
o
o
[
[
R
R
]
]
This tutorial shows how to create 2 Custom Views (Name & Image) and then how to create third one from these two.
Tutorial Call Custom Views shows how to use Structures to provide data for the View which is the approach used here.
We will use the same Structure and then each View will only take information that it needs.
UserName UserImage
UserNameImage
ContentView.swift
//================================================================================
// STRUCTURE: User
//================================================================================
struct User {
var firstName : String
var lastName : String
var imageName : String
}
//================================================================================
// STRUCTURE: ContentView
//================================================================================
struct ContentView: View {
let user = User(firstName: "John", lastName: "Carpenter", imageName: "Person")
var body: some View {
UserDetails(user: user)
.border(Color.red, width: 2)
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)
}
}
//================================================================================
// CSUTOM VIEW: UserName
//================================================================================
struct UserName: View {
//PARAMETERS
var user: User
//VIEW LAYOUT
var body: some View {
VStack {
HStack {
VStack(alignment: .leading) {
Text("First Name:").bold().padding(.bottom)
Text("Last Name:").bold()
}
VStack(alignment: .leading) {
Text(user.firstName).padding(.bottom)
Text(user.lastName)
}
}.frame(maxWidth: .infinity, alignment: .topLeading).padding()
}
}
}
//================================================================================
// CSUTOM VIEW: UserImage
//================================================================================
struct UserImage: View {
//PARAMETERS
var user: User
//VIEW LAYOUT
var body: some View {
VStack {
Image(user.imageName)
.resizable()
.aspectRatio(contentMode: .fit)
.border(Color.gray, width: 2)
.padding(.leading)
.padding(.trailing)
}
}
}
//================================================================================
// CSUTOM VIEW: UserNameImage
//================================================================================
struct UserDetails: View {
//PARAMETERS
var user: User
//VIEW LAYOUT
var body: some View {
VStack(alignment: .leading) {
UserName (user: user).border(Color.red, width: 2)
UserImage(user: user).border(Color.red, width: 2)
}
}
}